package com.home766.controller.admin;

import com.home766.dto.AreaDto;
import com.home766.dto.OrderExportDto;
import com.home766.dto.OrderItemExportDto;
import com.home766.util.poi.excel.BrowserUtils;
import com.home766.util.poi.excel.ExcelExportUtil;
import com.home766.util.poi.excel.entity.vo.ExcelTitle;
import net.biz.Page;
import net.biz.Pageable;
import net.biz.controller.admin.BaseController;
import net.biz.dto.OrderExport;
import net.biz.entity.Order;
import net.biz.entity.OrderItem;
import net.biz.service.AdminService;
import net.biz.service.AreaService;
import net.biz.service.OrderService;
import net.biz.service.ProductService;
import net.biz.util.JsonUtils;
import net.biz.util.ParamsUtil;
import net.biz.util.SpringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/orderReport")
public class OrderSalesReportController extends BaseController {
	
	@Resource(name="orderServiceImpl")
	private OrderService orderService;
	@Resource(name="areaServiceImpl")
	private AreaService areaService;
	@Resource(name="adminServiceImpl")
	private AdminService adminService;
	@Resource(name = "productServiceImpl")
	private ProductService productService;
	/**
	 * 
	 * @param model
	 * @param pageable
	 * @param reportType
	 * @param createDate
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="/list",method =RequestMethod.GET)
	public String list(ModelMap model, Pageable pageable, Integer reportType, String shopName, Date beginDate,
                       Date endDate, Date createDate, Long provinceId, Long cityId, Long areaId) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if(reportType == null){
			reportType = ParamsUtil.ORDER_REPORT_TYPE_RISE;
		}
		//查询所有订单
		Page<Order> page = orderService.findPage(null, null, beginDate, endDate, null, null, null, null, null, null, null, pageable, shopName, null, provinceId, cityId, areaId,true);
		//查询省份信息
		model.addAttribute("provinces", areaService.findRoots());
		if(provinceId != null){
			//查询市信息
			model.addAttribute("citys", areaService.findChildren(provinceId));			
		}
		if(cityId != null){
			//查询区信息
			model.addAttribute("areas", areaService.findChildren(cityId));						
		}
		model.addAttribute("page", page);
		model.addAttribute("reportType", reportType);
		model.addAttribute("shopName", shopName);
		model.addAttribute("provinceId", provinceId);
		model.addAttribute("cityId", cityId);
		model.addAttribute("areaId", areaId);
		if(beginDate!=null){
			model.addAttribute("beginDate",format.format(beginDate));
		}
		if(endDate!=null){
			model.addAttribute("endDate",format.format(endDate));
		}
		return "/admin/order/report";
	}
	
	/**
	 * 根据省份id查询市
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value="/findCitysByParentId",method = RequestMethod.POST)
	@ResponseBody
	public String findCitysByParentId(Long parentId){
		if(parentId == null){
			return null;
		}
		List<AreaDto> citys = areaService.findChildren(parentId);
		return JsonUtils.toJson(citys);
	}
	
	/**
	 * 根据市id查询区
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value="/findAreasByParentId",method = RequestMethod.POST)
	@ResponseBody
	public String findAreasByParentId(Long parentId){
		if(parentId == null){
			return null;
		}
		List<AreaDto> areas = areaService.findChildren(parentId);
		return JsonUtils.toJson(areas);
	}
	
	/**
     * 导出excel
     * 
     * @param request
     * @param response
     */
	@RequestMapping(value="/export",method = RequestMethod.GET)
    public void exportXls(Long provinceId, Long cityId, Long areaId, String shopName, Date beginDate, Date endDate, Date createDate, Integer exportType, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = "销售订单报表-抬头视图";
        if(exportType != null && exportType == 2){
        	codedFileName = "销售订单报表-项目视图";
        }
        OutputStream fOut = null;
        try {
            // 根据浏览器进行转码，使其支持中文文件名
            if (BrowserUtils.isIE(request)) {
                response.setHeader("content-disposition","attachment;filename=" + java.net.URLEncoder.encode(codedFileName, "UTF-8") + ".xls");
            } else {
                String newtitle = new String(codedFileName.getBytes("UTF-8"), "ISO8859-1");
                response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls");
            }
            // 产生工作簿对象
            HSSFWorkbook workbook = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<OrderExportDto> listDtos = new ArrayList<OrderExportDto>();
            List<OrderItemExportDto> listItemDtos = new ArrayList<OrderItemExportDto>();
            List<Order> list = orderService.findExportList(shopName,beginDate,endDate,createDate, provinceId, cityId, areaId);
            if(exportType != null && exportType == 1){
            	if(list.size() > 0){
            		for(Order order : list){
            			OrderExportDto dto = new OrderExportDto();
            			dto.setSn(order.getSn());
            			dto.setContract(order.getContract());
            			dto.setEngineering(order.getEngineering());
            			if(order.getOrderType()== ParamsUtil.CART_TYPE_SCHEME){
            				dto.setStatus(SpringUtils.getMessage("Order.OrderStatus."+order.getSchemeStatus()));
            			}else{
            				dto.setStatus(SpringUtils.getMessage("Order.OrderStatus."+order.getOrderStatus()));
            			}
            			dto.setShopName(order.getShops()==null?"":order.getShops().getShopsName());
            			dto.setServiceShopName(order.getServiceShops()==null?"":order.getServiceShops().getShopsName());
            			dto.setProvince(order.getArea()==null?"":order.getArea().getParent().getParent().getName());
            			dto.setCity(order.getArea()==null?"":order.getArea().getParent().getName());
            			dto.setArea(order.getArea()==null?"":order.getArea().getName());
            			dto.setPaymentMethodName(order.getPaymentMethodName());
            			dto.setShippingMethodName(order.getShippingMethodName());
            			dto.setCreateDate(dateFormat.format(order.getCreateDate()));
            			dto.setShopReward(order.getShopReward());
            			dto.setServiceShopReward(order.getServiceReward());
            			//添加到结果集合中
            			listDtos.add(dto);
            		}
            	}
            	workbook = ExcelExportUtil.exportExcel(new ExcelTitle(codedFileName, "导出人:"+adminService.getCurrent().getName(),"导出信息"), OrderExportDto.class, listDtos);
            }else if(exportType != null && exportType == 2){
            	if(list.size() > 0){
            		for(Order order : list){
            			OrderItemExportDto item = null;
            			if(order.getOrderType() == 1){
            				List<OrderItem> orderItems = order.getOrderItems();
            				//单品
            				for(int i = 0 ; i<orderItems.size() ; i++){
            					OrderItem oitem = orderItems.get(i);
            					item = new OrderItemExportDto();
            					item.setOrderSn(order.getSn());
                				item.setOrderType("单品订单");
                				item.setOrderTr("00"+(i+1));
                				item.setName(oitem.getName());
                				item.setSn(oitem.getSn());
                				item.setQuanlity(oitem.getQuantity());
                				item.setUnit(oitem.getProduct()==null?"":oitem.getProduct().getUnit());
                				item.setPrice(oitem.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                				item.setDiscount(BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP));
                				item.setSubtotal(oitem.getSubtotal().setScale(2, BigDecimal.ROUND_HALF_UP));
                				item.setSaleTax(oitem.getOutputTax().setScale(2, BigDecimal.ROUND_HALF_UP));
                				item.setShopReward(oitem.getShopReward());
                				item.setServiceShopReward(null);
                				//添加到结果集合中
                				listItemDtos.add(item);
            				}
            			}else{
            				//方案
            				item = new OrderItemExportDto();
            				item.setOrderSn(order.getSn());
            				item.setOrderType("方案订单");
            				item.setOrderTr("001");
            				item.setName(order.getSchemeName());
            				item.setSn(order.getSchemeSn());
            				item.setQuanlity(1);
            				item.setUnit("");
            				item.setPrice(order.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setDiscount(order.getPromotionDiscountScheme().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setSubtotal(order.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setSaleTax(order.getOutputTax().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setShopReward(order.getShopReward());
            				item.setServiceShopReward(order.getServiceReward());
            				//添加到结果集合中
            				listItemDtos.add(item);
            			}
            		}
            	}
            	workbook = ExcelExportUtil.exportExcel(new ExcelTitle(codedFileName, "导出人:"+adminService.getCurrent().getName(),"导出信息"), OrderItemExportDto.class, listItemDtos);
            }
			fOut = response.getOutputStream();
			workbook.write(fOut);
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {

            }
        }
    }
	/***
	 * 抬头视图和项目视图合并报表
	 * @param provinceId
	 * @param cityId
	 * @param areaId
	 * @param shopName
	 * @param createDate
	 * @param exportType
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/exportXlsToTotal",method = RequestMethod.GET)
    public void exportXlsToTotal(Long provinceId, Long cityId, Long areaId, String shopName, Date beginDate, Date endDate, Date createDate, Integer exportType, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = "销售订单报表视图";
        OutputStream fOut = null;
        try {
            // 根据浏览器进行转码，使其支持中文文件名
            if (BrowserUtils.isIE(request)) {
                response.setHeader("content-disposition","attachment;filename=" + java.net.URLEncoder.encode(codedFileName, "UTF-8") + ".xls");
            } else {
                String newtitle = new String(codedFileName.getBytes("UTF-8"), "ISO8859-1");
                response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls");
            }
            // 产生工作簿对象
            HSSFWorkbook workbook = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<OrderExport> listDtos = new ArrayList<OrderExport>();
            List<OrderItemExportDto> listItemDtos = new ArrayList<OrderItemExportDto>();
            List<Order> list = orderService.findExportList(shopName,beginDate,endDate,createDate, provinceId, cityId, areaId);
            List<OrderExport> orderItems = new ArrayList<OrderExport>();
        	if(list.size() > 0){
        		for(Order order : list){
        			if(order.getOrderType() == 1){
        				//单品
        				for(int i = 0 ; i<order.getOrderItems().size() ; i++){
        					OrderExport item = new OrderExport();
        					//添加订单头
        					item.setSn(order.getSn());
        					item.setContract(order.getContract());
        					item.setEngineering(order.getEngineering());
        					item.setStatus(SpringUtils.getMessage("Order.OrderStatus."+order.getOrderStatus()));
        					item.setPaymentStatus(SpringUtils.getMessage("Order.PaymentStatus."+order.getPaymentStatus()));
        					item.setShopName(order.getShops()==null?"":order.getShops().getShopsName());
        					item.setServiceShopName(order.getServiceShops()==null?"":order.getServiceShops().getShopsName());
        					item.setFullName(order.getArea().getFullName());
        					item.setPaymentMethodName(order.getPaymentMethodName());
        					item.setShippingMethodName(order.getShippingMethodName());
        					item.setCreateDate(dateFormat.format(order.getCreateDate()));
        					//新增报表字段，金额
        					if(i>0){
        						item.setFreight(new BigDecimal("0.00"));
        						item.setOtherMoney(new BigDecimal("0.00"));
        						item.setPromotionDiscountScheme(new BigDecimal("0.00"));
        						item.setFee(new BigDecimal("0.00"));
        					}else{
        						item.setFreight(order.getFreight());
        						item.setOtherMoney(order.getOffsetAmount());
        						item.setPromotionDiscountScheme(order.getPromotionDiscountScheme());
        						item.setFee(order.getFee());
        					}
        					item.setPercentPrice(order.getPercentPrice());
        					item.setInstallCost(order.getInstallCost());
        					
        					item.setPercent(order.getPercent());
        					item.setPercentPricePaid(order.getPercentPricePaid());
        					//订单项
        					item.setOrderSn(order.getSn());
            				item.setOrderType("单品订单");
            				item.setOrderTr("00"+(i+1));
            				item.setName(order.getOrderItems().get(i).getName());
            				item.setSn(order.getOrderItems().get(i).getSn());
            				item.setQuanlity(order.getOrderItems().get(i).getQuantity());
            				item.setUnit(order.getOrderItems().get(i).getProduct()==null?"":order.getOrderItems().get(i).getProduct().getUnit());
            				item.setPrice(order.getOrderItems().get(i).getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setDiscount(BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setSubtotal(order.getOrderItems().get(i).getSubtotal().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setSaleTax(order.getOrderItems().get(i).getOutputTax().setScale(2, BigDecimal.ROUND_HALF_UP));
            				item.setShopReward(order.getOrderItems().get(i).getShopReward()==null?new BigDecimal("0"):order.getOrderItems().get(i).getShopReward());
            				item.setServiceShopReward(null);
            				//添加
            				orderItems.add(item);
        				}
        			}else{
        				//方案
    					//添加订单头
        				OrderExport item = new OrderExport();
    					item.setSn(order.getSn());
    					item.setContract(order.getContract());
    					item.setEngineering(order.getEngineering());
    					item.setStatus(SpringUtils.getMessage("Order.OrderStatus."+order.getSchemeStatus()));
    					System.out.println(SpringUtils.getMessage("Order.OrderStatus."+order.getOrderStatus()));
    					item.setPaymentStatus(SpringUtils.getMessage("Order.PaymentStatus."+order.getPaymentStatus()));
    					item.setShopName(order.getShops()==null?"":order.getShops().getShopsName());
    					item.setServiceShopName(order.getServiceShops()==null?"":order.getServiceShops().getShopsName());
    					item.setFullName(order.getArea().getFullName());
    					item.setPaymentMethodName(order.getPaymentMethodName());
    					item.setShippingMethodName(order.getShippingMethodName());
    					item.setCreateDate(dateFormat.format(order.getCreateDate()));
    					//新增报表字段，金额
    					item.setPromotionDiscountScheme(order.getPromotionDiscountScheme());
    					item.setOtherMoney(order.getOtherMoney());
    					item.setFreight(order.getFreight());
    					item.setPercentPrice(order.getAmountPayable());
    					item.setInstallCost(order.getInstallCost());
    					item.setFee(order.getFee());
    					item.setPercent(order.getPercent());
    					item.setPercentPricePaid(order.getPercentPricePaid());
    					item.setSchemeArea(order.getSchemeArea()+order.getShopSchemeArea());
    					
        				item.setOrderSn(order.getSn());
        				item.setOrderType("方案订单");
        				item.setOrderTr("001");
        				item.setName(order.getSchemeName());
        				item.setSn(order.getSchemeSn());
        				item.setQuanlity(1);
        				item.setUnit("");
        				item.setPrice(order.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
        				item.setDiscount(order.getPromotionDiscountScheme().setScale(2, BigDecimal.ROUND_HALF_UP));
        				item.setSubtotal(order.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
        				item.setSaleTax(order.getOutputTax().setScale(2, BigDecimal.ROUND_HALF_UP));
        				item.setShopReward(order.getShopReward()==null?new BigDecimal("0"):order.getShopReward());
        				item.setServiceShopReward(order.getServiceReward()==null?new BigDecimal("0"):order.getServiceReward());
        				//添加
        				orderItems.add(item);
        			}
        		}
        	}
            workbook = ExcelExportUtil.exportExcel(new ExcelTitle(codedFileName, "导出人:"+adminService.getCurrent().getName(),"导出信息"), OrderExport.class, orderItems);
/*            HSSFCellStyle hlink_style = workbook.createCellStyle();
            HSSFFont hlink_font = workbook.createFont();
            hlink_font.setUnderline(HSSFFont.U_SINGLE);
            hlink_font.setColor(HSSFColor.BLUE.index); 
            hlink_style.setFont(hlink_font);
            HSSFSheet sheet = workbook.getSheet(workbook.getSheetName(0));
            for(int j=0;j<sheet.getLastRowNum()-3;j++){
            	HSSFCell cell;
            	HSSFRow row;
            	row = sheet.createRow(j+2);
            	cell= row.createCell(0);
                System.out.println(orderItems.get(j).getSn());
                cell.setCellValue("");
                HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                link.setAddress("http://www.766home.com");
                cell.setHyperlink(link);
                cell.setCellStyle(hlink_style);
            }*/
            
            
/*            System.out.println("行数："+sheet.getLastRowNum());
            System.out.println(sheet.getRow(2).getCell(0));
            row = sheet.getRow(2);
            cell = row.getCell(0);
            System.out.println(cell.getStringCellValue());
            //System.out.println(cell.getStringCellValue());
            cell = sheet.createRow(2).createCell((short)0);
            cell.setCellValue(cell.getStringCellValue());
            //cell.setCellFormula("HYPERLINK(\"" + "www.baidu.com"+ "\",\"" + "baidu"+ "\")");
            HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
            link.setAddress("http://www.766home.com");
            cell.setHyperlink(link);
            cell.setCellStyle(hlink_style);*/
            fOut = response.getOutputStream();
			workbook.write(fOut);
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {

            }
        }
    }
}
